//
//  ZXContentAutoFit.m
//  ZXContentAutoFit
//
//  Created by LIUKUN-PC on 16/5/10.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "ZXContentAutoFit.h"

@implementation NSString (ContentAutoFit)

- (CGFloat)heightWithMaxWidth:(CGFloat)width fontSize:(CGFloat)fontSize {
    return [self sizeWithMaxSize:CGSizeMake(width, CGFLOAT_MAX) fontSize:fontSize].height;
}

- (CGFloat)widthWithMaxHeight:(CGFloat)height fontSize:(CGFloat)fontSize {
    
    return [self sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, height) fontSize:fontSize].width;
}

- (CGSize)sizeWithMaxSize:(CGSize)size fontSize:(CGFloat)fontSize {
    UIFont * font = [UIFont systemFontOfSize:fontSize];
    return [self sizeWithMaxSize:size font:font];
}

- (CGFloat)heightWithMaxWidth:(CGFloat)width font:(UIFont *)font {
    return [self sizeWithMaxSize:CGSizeMake(width, CGFLOAT_MAX) font:font].height;
}

- (CGFloat)widthWithMaxHeight:(CGFloat)height font:(UIFont *)font {
    
    return [self sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, height) font:font].width;
}

- (CGSize)sizeWithMaxSize:(CGSize)size font:(UIFont *)font {
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    size = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    size.height = ceil(size.height);
    size.width = ceil(size.width);
    return size;

}

@end

@implementation NSAttributedString (ContentAutoFit)

- (CGFloat)heightWithMaxWidth:(CGFloat)width {
    return [self sizeWithMaxSize:CGSizeMake(width, CGFLOAT_MAX)].height;
}

- (CGFloat)widthWithMaxHeight:(CGFloat)height {
    
    return [self sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, height)].width;
}

- (CGSize)sizeWithMaxSize:(CGSize)size {
    size = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    size.height = ceil(size.height);
    size.width = ceil(size.width);
    return size;
}


@end

